package org.boot.easyapi.permission.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.boot.easyapi.permission.service.PermissionService;
import org.boot.easyapi.properties.EasyApiProperties;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static org.boot.easyapi.pojo.web.CommonResult.error;

/**
 * 认证用户信息赋予 - 过滤器
 */
@Slf4j
@Order(88)
@Component
@WebFilter(filterName = "easyapi-authenticationUserFilter", urlPatterns = "/*")
public class EasyApiAuthenticationUserFilter implements Filter {

    private final Integer ERROR_CODE = 1501;

    @Resource
    private PermissionService permissionService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if(increasingPermission(request)){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            errorResponse(response, "该用户/IP没有权限访问!");
        }
    }


    /**
     * 检查是否有权限
     */
    private boolean increasingPermission(HttpServletRequest request) {
        EasyApiProperties properties = EasyApiProperties.properties();
        boolean flag = true;
        //ip权限
        if (properties.getWeb().getPermission().isIpEnabled() ) {
            if(!permissionService.hasIpPermission(request)){
                log.warn("IP访问被拒-->IP: {}", request.getRemoteAddr());
                flag = false;
            }else{
                log.info("IP访问通行-->IP: {}", request.getRemoteAddr());
            }
        }
        //用户访问路径权限
        if(properties.getWeb().getPermission().isUserEnabled() ){
            if (!permissionService.hasPathPermission(request)){
                log.warn("用户访问被拒-->路径: {}", request.getRequestURI());
                flag = false;
            } else{
                log.info("用户访问通行-->路径: {}", request.getRequestURI());
                flag = true;
            }
        }
        return flag;
    }


    private void errorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(error(ERROR_CODE, message)));
        writer.flush();
    }


}
